package studio.raptor.dispatcher.server.handler.consumption;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import studio.raptor.databus.command.EventMetaData;
import studio.raptor.dispatcher.server.context.HandlerContext;
import studio.raptor.dispatcher.server.handler.Handler;
import studio.raptor.dispatcher.server.service.CacheService;

/**
 * 幂等性处理，校验消息是否已经发送过
 *
 * @author jack
 * @since 1.0
 */
@Component
public class IdempotenceHandler extends Handler {

  private static final Logger log = LoggerFactory.getLogger(IdempotenceHandler.class);

  @Autowired
  CacheService cacheService;

  @Override
  public boolean process(HandlerContext context) {
    String code = context.getCode();
    Integer kindId = context.getKindId();
    Integer eventType = context.getEventType();

    EventMetaData metaData = context.getEvent().getEventMetaData();
    String orderId = metaData.getBusinessNo();
    String body = context.getEvent().getEventBusinessData().getContent();
    boolean result = cacheService.verify(code, kindId, eventType, metaData);
    log.debug(" the order [{}] has {} been sent to [{}]", orderId, result ? "not" : " ",
        code);
    if (result) {
      //事件的消息体不存在
      if (!Strings.isNullOrEmpty(body)) {
        cacheService.saveEventBody(orderId, kindId, eventType, body);
      }
      result = getSuccessor().process(context);
    }
    return result;
  }

}
